/**
 *博尔信基础开发平台
 *<br> 版权声明：厦门博尔信软件有限公司版权所有,违者必究
 *<br> Copyright:  Copyright (c) 2012
 *<br> Company:pearlsoft
 *<br> @author 蒋勇华
 *<br> 2012-5-15
 *<br> @version 1.0
 *————————————————————————————————————
 *修改记录
 *    修改者：
 *    修改时间：
 *    修改原因：
 *——————————————————————————————————————
 */
package com.pearlsoft.webapp.rms.resrun.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pearlsoft.rms.VappConfig;
import com.pearlsoft.rms.VcloudManager;
import com.pearlsoft.util.DateUtils;
import com.pearlsoft.webapp.core.WebException;
import com.pearlsoft.webapp.core.dao.RecrodRowMapper;
import com.pearlsoft.webapp.core.dataset.Record;
import com.pearlsoft.webapp.core.dataset.SimpleRecord;
import com.pearlsoft.webapp.core.service.BaseSimpleJdbcService;
import com.pearlsoft.webapp.rms.StepStatus;
import com.pearlsoft.webapp.rms.resapply.service.ResApplyService;

/**
 *描述： 
 *
 * 
 */
@Service
public class ResRunService extends BaseSimpleJdbcService{
	@Autowired
	private VcloudManager vcloudManager;
	@Autowired
	private ResApplyService resApplyService;
	protected VcloudManager getVcloudManager(){
		return this.vcloudManager;
	}
	protected ResApplyService getResApplyService(){
		return this.resApplyService;
	}
	
	public Record getById(String stepId){
		String sql = "SELECT stepId,opinion,result,checkReport,flowId,applyId,result  FROM rms_flowstep  WHERE stepId=:stepId";
		Map<String,String> param = new HashMap<String,String>();
		param.put("stepId", stepId);
		Record record = this.getBaseSimpleJdbcDao().queryOne(sql,param,
			new  RecrodRowMapper<Record>(){
				@Override
				public Record mapRow(ResultSet rs, int rowNum)
						throws SQLException {				
					SimpleRecord recrod = new SimpleRecord();
					recrod.setValue("stepId", rs.getString(1));
					recrod.setValue("opinion", rs.getString(2));
					recrod.setValue("result", rs.getString(3));
					recrod.setValue("checkReport", rs.getString(4));	
					recrod.setValue("flowId", rs.getString(5));
					recrod.setValue("applyId", rs.getString(6));
					recrod.setValue("result", rs.getString(7));
					
					return recrod;
				}
			});
		return record;
	}
	/***
	 * 保存处理
	 * @param record
	 * @throws WebException
	 */
	public void save(Record record) throws WebException{
		String stepId =(String)record.getValue("stepId");
		String result =(String)record.getValue("result");
		String opinion =(String)record.getValue("opinion");
		String sql=" update rms_flowstep set result=:result,opinion=:opinion where stepId=:stepId";
		Map<String,String> param = new HashMap<String,String>();
		param.put("result", result);
		param.put("opinion", opinion);
		param.put("stepId", stepId);
		this.getBaseSimpleJdbcDao().update(sql, param);
	}
	
	/***
	 * 资源配置审批提交
	 * @param record
	 * @throws WebException
	 */
	public void apply(Record record)throws WebException{
		//保存或者更新资源配置审批
		this.save(record);
		String stepId =(String)record.getValue("stepId");
		//更新步骤状态
		String sql =" update rms_flowstep  set stepstatus=:stepstatus, endTime=:endTime where stepId=:stepId  ";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("stepId", stepId);
		param.put("endTime", DateUtils.getCurrentDate());
		param.put("stepstatus", StepStatus.DEALED);
		this.getBaseSimpleJdbcDao().update(sql, param);
		//结束流程
		this.endFlow(stepId);
	}
	
	public Record run(Record record) {
		Record result = new SimpleRecord();
		result.setValue("success", "1");
		result.setValue("error", "");
		String stepId =(String)record.getValue("stepId");
		try{
			Record currentStep = this.getById(stepId);
			String applyId = (String)currentStep.getValue("applyId");
			Record applyObj=this.getResApplyService().getById(applyId);
			List<Map> hostList =(List<Map>) applyObj.getValue("hostList");
	        VappConfig config = new VappConfig("vapp100");
	        config.setOrgName("test");
	        config.setVdcName("test");
	        for(Map map:hostList){
	        	String hostName = (String) map.get("hostName");
	        	String hostIp = (String) map.get("hostIp");
	        	List<String> hostIpList = new ArrayList<String>();
	        	if(StringUtils.isBlank(hostIp)){
	        		String[] ips = hostIp.split(",");
	        		for(int i=0;i<ips.length;i++){
	        			String ip = ips[i];
	        			if(StringUtils.isBlank(ip)){
	        				hostIpList.add(ip);
	        			}
	        		}
	        	}
	        	
	        	int intCups =Integer.parseInt( (String) map.get("cups"));
	        	int intNetcards =Integer.parseInt( (String) map.get("netcards"));
	        	String memoryunit = (String) map.get("memoryunit");
	        	String memory = (String) map.get("memory");
	        	int intMemory =0;
	        	if("0".equalsIgnoreCase(memoryunit)){//M
	        		intMemory = Integer.parseInt(memory);
	        	}else if("1".equalsIgnoreCase(memoryunit) ){//G
	        		intMemory = Integer.parseInt(memory)*1024;
	        	}
	        	String storageunit = (String) map.get("storageunit");
	        	String storage = (String) map.get("storage");
	        	int intStorage =0;
	        	if("0".equalsIgnoreCase(storageunit)){//M
	        		intStorage = Integer.parseInt(storage);
	        	}else if("1".equalsIgnoreCase(storageunit) ){//G
	        		intStorage = Integer.parseInt(storage)*1024;
	        	}else if("2".equalsIgnoreCase(storageunit) ){//T
	        		intStorage = Integer.parseInt(storage)*1024*1024;
	        	}        	
	            config.addVm(hostName, "XP", intCups, intNetcards, intMemory, intStorage, 8,hostIpList);
	        }
			//this.getVappCreator().create(config);
	        this.updateRunStatus(stepId, "1");
		}catch(Exception e){
			result.setValue("success", "0");
			result.setValue("error", e.getMessage());
			this.updateRunStatus(stepId, "0");
		}
		return result;
	}
	
	/***
	 * 更新执行状态
	 * @param record
	 * @throws WebException
	 */
	private void updateRunStatus(String stepId,String result){
		//更新执行状态
		String sql =" update rms_flowstep  set result=:result where stepId=:stepId  ";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("stepId", stepId);
		param.put("result", result);
		this.getBaseSimpleJdbcDao().update(sql, param);
	}
	
	/***
	 * 结束流程
	 * @param record
	 * @throws WebException
	 */
	private void endFlow(String preStepId) throws WebException{
		Record preStep = this.getById(preStepId);
		String applyId = (String) preStep.getValue("applyId");
		String result = (String) preStep.getValue("result");
		Map<String, Object> param = new HashMap<String, Object>();
		//把申请步骤设置为完成
		String sql="update rms_flowstep t set t.stepstatus=:stepstatus where t.applyId=:applyId and t.stepType='0'";
		param.put("applyId", applyId);
		if("2".equalsIgnoreCase(result)){
			param.put("stepstatus", StepStatus.ENDSUCCESS);
		}else if("3".equalsIgnoreCase(result)){
			param.put("stepstatus", StepStatus.ENDFAIL);
		}
		//插入个人资源表
		this.getBaseSimpleJdbcDao().update(sql, param);
	}
	
}
